#ifndef DATABASE_MANAGER_H
#define DATABASE_MANAGER_H

#include <mysql/mysql.h>
#include <string>
#include <vector>
#include <memory>
#include <mutex>
#include <queue>
#include <condition_variable>
#include <thread>
#include <chrono>
#include "enhanced_chat_system.h"

// MySQL连接配置
struct DatabaseConfig {
    std::string host = "127.0.0.1";
    std::string username = "root";
    std::string password = "";
    std::string database = "enhanced_chat_db";
    unsigned int port = 3306;
    int pool_size = 10;
    int timeout = 30;
};

// MySQL连接池
class MySQLConnectionPool {
private:
    std::queue<MYSQL*> connections;
    std::mutex mutex;
    std::condition_variable condition;
    DatabaseConfig config;
    bool initialized;
    
public:
    MySQLConnectionPool(const DatabaseConfig& cfg);
    ~MySQLConnectionPool();
    
    bool initialize();
    void cleanup();
    MYSQL* getConnection();
    void releaseConnection(MYSQL* conn);
    
private:
    MYSQL* createConnection();
    bool isConnectionValid(MYSQL* conn);
};

// RAII MySQL连接管理器
class MySQLConnection {
private:
    MYSQL* connection;
    MySQLConnectionPool* pool;
    
public:
    MySQLConnection(MySQLConnectionPool* p);
    ~MySQLConnection();
    
    MYSQL* get() { return connection; }
    operator bool() const { return connection != nullptr; }
    
    // 禁用拷贝
    MySQLConnection(const MySQLConnection&) = delete;
    MySQLConnection& operator=(const MySQLConnection&) = delete;
};

// 数据库管理器
class DatabaseManager {
private:
    std::unique_ptr<MySQLConnectionPool> connectionPool;
    DatabaseConfig config;
    
public:
    DatabaseManager(const DatabaseConfig& cfg = DatabaseConfig{});
    ~DatabaseManager();
    
    bool initialize();
    void cleanup();
    
    // 用户管理
    bool insertUser(const std::shared_ptr<UserInfo>& user);
    bool updateUser(const std::shared_ptr<UserInfo>& user);
    bool deleteUser(const std::string& userId);
    std::shared_ptr<UserInfo> getUser(const std::string& userId);
    std::vector<std::shared_ptr<UserInfo>> getOnlineUsers();
    bool updateUserStatus(const std::string& userId, UserStatus status);
    bool updateUserActivity(const std::string& userId);
    
    // 私聊管理
    bool insertPrivateChat(const std::shared_ptr<PrivateChat>& chat);
    bool updatePrivateChatActivity(const std::string& chatId);
    std::shared_ptr<PrivateChat> getPrivateChat(const std::string& chatId);
    std::vector<std::string> getUserPrivateChats(const std::string& userId);
    
    // 群组管理
    bool insertGroup(const std::shared_ptr<GroupInfo>& group);
    bool updateGroup(const std::shared_ptr<GroupInfo>& group);
    bool deleteGroup(const std::string& groupId);
    std::shared_ptr<GroupInfo> getGroup(const std::string& groupId);
    std::vector<std::shared_ptr<GroupInfo>> getUserGroups(const std::string& userId);
    
    // 群组成员管理
    bool addGroupMember(const std::string& groupId, const std::string& userId, GroupRole role = ROLE_MEMBER);
    bool removeGroupMember(const std::string& groupId, const std::string& userId);
    bool updateGroupMemberRole(const std::string& groupId, const std::string& userId, GroupRole role);
    std::vector<std::string> getGroupMembers(const std::string& groupId);
    
    // 消息管理
    bool insertMessage(const EnhancedMessage& message);
    std::vector<EnhancedMessage> getPrivateMessages(const std::string& user1, const std::string& user2, 
                                                   int limit = 50, int offset = 0);
    std::vector<EnhancedMessage> getGroupMessages(const std::string& groupId, 
                                                 int limit = 50, int offset = 0);
    std::vector<EnhancedMessage> getRecentMessages(const std::string& userId, int limit = 20);
    
    // 统计信息
    int getUserMessageCount(const std::string& userId);
    int getGroupMessageCount(const std::string& groupId);
    
private:
    // 工具方法
    std::string escapeString(const std::string& str);
    std::string timeToString(time_t timestamp);
    time_t stringToTime(const std::string& str);
    
    // 结果集转换
    std::shared_ptr<UserInfo> resultToUser(MYSQL_RES* result);
    std::shared_ptr<PrivateChat> resultToPrivateChat(MYSQL_RES* result);
    std::shared_ptr<GroupInfo> resultToGroup(MYSQL_RES* result);
    EnhancedMessage resultToMessage(MYSQL_RES* result);
    
    // 错误处理
    void logError(MYSQL* conn, const std::string& operation);
    bool executeQuery(MYSQL* conn, const std::string& query);
    MYSQL_RES* executeSelect(MYSQL* conn, const std::string& query);
};

// 全局数据库管理器实例
extern std::unique_ptr<DatabaseManager> g_databaseManager;

// 初始化数据库管理器
bool initializeDatabase(const DatabaseConfig& config = DatabaseConfig{});
void cleanupDatabase();

#endif // DATABASE_MANAGER_H 